#include <modbus/modbus.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char *argv[]) {
      printf("usb entry:%s\n", argv[1]);
    printf("dev address:%s\n", argv[2]);

    modbus_t *ctx;
    uint16_t temp;
    int ret;

    ctx = modbus_new_rtu( argv[1], 9600, 'N', 8, 1);
    if (ctx == NULL) {
        fprintf(stderr, "Unable to create the libmodbus context\n");
        return -1;
    }
    // int *address=(int*)argv[2];
    //  intptr_t num = (intptr_t)address;
    //  printf("num:%ld\n",num);

     int result;

    result = strtol(argv[2], NULL, 16);

    printf("Integer value: %d\n", result);


    modbus_set_slave(ctx, result ); // 设置Modbus从机地址

    if (modbus_connect(ctx) == -1) {
        fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }

    // 读取TH10S-B传感器的温度，从寄存器地址0开始，读取1个寄存器
    ret = modbus_read_registers(ctx, 0, 1, &temp);
    if (ret == -1) {
        fprintf(stderr, "Read failed: %s\n", modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }
    
    printf("Temperature: %0.1f °C\n", temp / 10.0);

    modbus_close(ctx);
    modbus_free(ctx);

    return 0;
}